/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * LatLonJsToMySQL.java
 *
 * Created on 18-mar-2010, 0.49.47
 */
package freimapgsoc;

import com.mysql.jdbc.Connection;
import com.mysql.jdbc.Statement;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.Frame;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.io.BufferedReader;
import java.io.File;
import java.io.InputStreamReader;
import java.net.URL;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.StringTokenizer;
import java.util.Vector;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JOptionPane;

/**
 *
 * @author Stefano
 */
public class MySQLCredential extends javax.swing.JFrame {

    /** Creates new form LatLonJsToMySQL */
    public MySQLCredential(DataSource datas) {
        this.datas = datas;
        initComponents();
    }

    /**
     * This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     * @return
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        confirmPane = new JOptionPane("If you continue your current data in the Database will be destroyed. \n Are you sure that you want to continue?.\n", JOptionPane.QUESTION_MESSAGE, JOptionPane.YES_NO_OPTION);
        ;
        scrollPane = new javax.swing.JScrollPane();
        errorsLog = new javax.swing.JTextArea();
        cancelButton = new javax.swing.JButton();
        startButton = new javax.swing.JButton();
        logLabel = new javax.swing.JLabel();
        jLabel7 = new javax.swing.JLabel();
        showLog = new javax.swing.JButton();
        newDb = new javax.swing.JCheckBox();
        newDbText = new javax.swing.JTextField();
        continueButton = new javax.swing.JButton();
        resumeButton = new javax.swing.JButton();
        jPanel1 = new javax.swing.JPanel();
        hostText = new javax.swing.JTextField();
        portText = new javax.swing.JTextField();
        jLabel6 = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        passwordText = new javax.swing.JPasswordField();
        userText = new javax.swing.JTextField();
        jLabel3 = new javax.swing.JLabel();
        checkconnButton = new javax.swing.JButton();
        exampleButton = new javax.swing.JButton();
        dbText = new javax.swing.JComboBox();
        jLabel4 = new javax.swing.JLabel();

        confirmPane.setMessage("If you continue your current data in the Database will be destroyed. \n Are you sure that you want to continue?.\n");
        confirmPane.setFont(new java.awt.Font("Lucida Grande", 1, 10));
        confirmPane.setName("confirmPane"); // NOI18N
        confirmPane.addPropertyChangeListener(new java.beans.PropertyChangeListener() {
            public void propertyChange(java.beans.PropertyChangeEvent evt) {
                confirmPanePropertyChange(evt);
            }
        });

        scrollPane.setName("scrollPane"); // NOI18N
        scrollPane.setSize(new java.awt.Dimension(400, 300));

        errorsLog.setColumns(20);
        errorsLog.setEditable(false);
        errorsLog.setFont(new java.awt.Font("Lucida Grande", 0, 10));
        errorsLog.setRows(8);
        errorsLog.setTabSize(10);
        errorsLog.setName("errorsLog"); // NOI18N
        errorsLog.setPreferredSize(new java.awt.Dimension(400, 300));
        errorsLog.setSize(new java.awt.Dimension(300, 400));
        scrollPane.setViewportView(errorsLog);

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("MySQL Credentials");

        cancelButton.setFont(new java.awt.Font("Lucida Grande", 0, 10));
        cancelButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/freimapgsoc/resources/Error.png"))); // NOI18N
        cancelButton.setText("Cancel");
        cancelButton.setName("cancelButton"); // NOI18N
        cancelButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cancelButtonActionPerformed(evt);
            }
        });

        startButton.setFont(new java.awt.Font("Lucida Grande", 0, 10));
        startButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/freimapgsoc/resources/statuok.png"))); // NOI18N
        startButton.setText("Create");
        startButton.setEnabled(false);
        startButton.setName("startButton"); // NOI18N
        startButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                startButtonActionPerformed(evt);
            }
        });

        logLabel.setFont(new java.awt.Font("Lucida Grande", 0, 10)); // NOI18N
        logLabel.setText(" ");
        logLabel.setName("logLabel"); // NOI18N

        jLabel7.setFont(new java.awt.Font("Lucida Grande", 0, 12));
        jLabel7.setIcon(new javax.swing.ImageIcon(getClass().getResource("/freimapgsoc/resources/download.png"))); // NOI18N
        jLabel7.setText("Insert MySQL credential to store the data of the Mesh Network:");
        jLabel7.setName("jLabel7"); // NOI18N

        showLog.setFont(new java.awt.Font("Lucida Grande", 0, 10));
        showLog.setIcon(new javax.swing.ImageIcon(getClass().getResource("/freimapgsoc/resources/txtdocs.png"))); // NOI18N
        showLog.setText("Show Log");
        showLog.setName("showLog"); // NOI18N
        showLog.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                showLogActionPerformed(evt);
            }
        });

        newDb.setFont(new java.awt.Font("Lucida Grande", 0, 10));
        newDb.setText("I want to create a new Database:");
        newDb.setEnabled(false);
        newDb.setName("newDb"); // NOI18N
        newDb.addItemListener(new java.awt.event.ItemListener() {
            public void itemStateChanged(java.awt.event.ItemEvent evt) {
                newDbItemStateChanged(evt);
            }
        });

        newDbText.setFont(new java.awt.Font("Lucida Grande", 0, 12));
        newDbText.setEnabled(false);
        newDbText.setName("newDbText"); // NOI18N

        continueButton.setFont(new java.awt.Font("Lucida Grande", 0, 10));
        continueButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/freimapgsoc/resources/statuok.png"))); // NOI18N
        continueButton.setText("Continue without store data");
        continueButton.setEnabled(false);
        continueButton.setName("continueButton"); // NOI18N
        continueButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                continueButtonActionPerformed(evt);
            }
        });

        resumeButton.setFont(new java.awt.Font("Lucida Grande", 0, 10));
        resumeButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/freimapgsoc/resources/statuok.png"))); // NOI18N
        resumeButton.setText("Resume from the selected Database");
        resumeButton.setEnabled(false);
        resumeButton.setName("resumeButton"); // NOI18N
        resumeButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                resumeButtonActionPerformed(evt);
            }
        });

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("Database"));
        jPanel1.setName("jPanel1"); // NOI18N

        hostText.setFont(new java.awt.Font("Lucida Grande", 0, 12));
        hostText.setName("hostText"); // NOI18N

        portText.setFont(new java.awt.Font("Lucida Grande", 0, 12));
        portText.setText("3306");
        portText.setName("portText"); // NOI18N

        jLabel6.setText(":");
        jLabel6.setName("jLabel6"); // NOI18N

        jLabel5.setFont(new java.awt.Font("Lucida Grande", 0, 10));
        jLabel5.setText("Hostname/IP:");
        jLabel5.setName("jLabel5"); // NOI18N

        jLabel2.setFont(new java.awt.Font("Lucida Grande", 0, 10));
        jLabel2.setText("Password:");
        jLabel2.setName("jLabel2"); // NOI18N

        passwordText.setFont(new java.awt.Font("Lucida Grande", 0, 12));
        passwordText.setName("passwordText"); // NOI18N

        userText.setFont(new java.awt.Font("Lucida Grande", 0, 12));
        userText.setName("userText"); // NOI18N

        jLabel3.setFont(new java.awt.Font("Lucida Grande", 0, 10));
        jLabel3.setText("UserName:");
        jLabel3.setName("jLabel3"); // NOI18N

        checkconnButton.setFont(new java.awt.Font("Lucida Grande", 0, 10));
        checkconnButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/freimapgsoc/resources/zoom.png"))); // NOI18N
        checkconnButton.setText("Connect");
        checkconnButton.setName("checkconnButton"); // NOI18N
        checkconnButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                checkconnButtonActionPerformed(evt);
            }
        });

        exampleButton.setFont(new java.awt.Font("Lucida Grande", 0, 10));
        exampleButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/freimapgsoc/resources/clone.png"))); // NOI18N
        exampleButton.setText("Example");
        exampleButton.setName("exampleButton"); // NOI18N
        exampleButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                exampleButtonActionPerformed(evt);
            }
        });

        org.jdesktop.layout.GroupLayout jPanel1Layout = new org.jdesktop.layout.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(jPanel1Layout.createSequentialGroup()
                .add(7, 7, 7)
                .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING)
                    .add(jPanel1Layout.createSequentialGroup()
                        .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING)
                            .add(jLabel3)
                            .add(jLabel2))
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                        .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING, false)
                            .add(passwordText)
                            .add(userText, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 160, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)))
                    .add(jPanel1Layout.createSequentialGroup()
                        .add(jLabel5)
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                        .add(hostText, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 160, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)))
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(jLabel6)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(portText, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 53, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                    .add(jPanel1Layout.createSequentialGroup()
                        .add(checkconnButton)
                        .add(18, 18, 18)
                        .add(exampleButton, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 88, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap(40, Short.MAX_VALUE))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(jPanel1Layout.createSequentialGroup()
                .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(jLabel6)
                    .add(hostText, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                    .add(jLabel5)
                    .add(portText, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(jLabel3)
                    .add(userText, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(passwordText, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                    .add(jLabel2)
                    .add(checkconnButton, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 35, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                    .add(exampleButton, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 35, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        dbText.setFont(new java.awt.Font("Lucida Grande", 0, 12));
        dbText.setEnabled(false);
        dbText.setName("dbText"); // NOI18N

        jLabel4.setFont(new java.awt.Font("Lucida Grande", 0, 10));
        jLabel4.setText("Avaible Database:");
        jLabel4.setName("jLabel4"); // NOI18N

        org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(layout.createSequentialGroup()
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(layout.createSequentialGroup()
                        .addContainerGap()
                        .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                            .add(jLabel7)
                            .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING, false)
                                .add(org.jdesktop.layout.GroupLayout.LEADING, jPanel1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                                .add(layout.createSequentialGroup()
                                    .add(24, 24, 24)
                                    .add(jLabel4)
                                    .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                                    .add(dbText, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 226, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                                    .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                    .add(showLog, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 92, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)))))
                    .add(layout.createSequentialGroup()
                        .add(28, 28, 28)
                        .add(newDb)
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                        .add(newDbText, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 160, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                    .add(layout.createSequentialGroup()
                        .add(19, 19, 19)
                        .add(logLabel, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 253, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                        .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                            .add(resumeButton, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 251, Short.MAX_VALUE)
                            .add(continueButton, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 251, Short.MAX_VALUE)
                            .add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup()
                                .add(cancelButton, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 120, Short.MAX_VALUE)
                                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                                .add(startButton, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 127, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)))))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(layout.createSequentialGroup()
                .add(21, 21, 21)
                .add(jLabel7)
                .add(18, 18, 18)
                .add(jPanel1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED)
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(jLabel4)
                    .add(dbText, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                    .add(showLog))
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED)
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(layout.createSequentialGroup()
                        .add(newDbText, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                        .add(18, 18, 18)
                        .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                            .add(startButton)
                            .add(cancelButton)))
                    .add(layout.createSequentialGroup()
                        .add(2, 2, 2)
                        .add(newDb)))
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(logLabel, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 77, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                    .add(layout.createSequentialGroup()
                        .add(continueButton)
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                        .add(resumeButton)))
                .addContainerGap(org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void cancelButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cancelButtonActionPerformed
        Component source = (Component) evt.getSource();
        int i = confirmPane.showConfirmDialog(source, "Are you sure?", "Exit", JOptionPane.YES_NO_OPTION);
        if (i == 0) {
            this.dispose();
        }
}//GEN-LAST:event_cancelButtonActionPerformed

    private void startButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_startButtonActionPerformed
        try {
            if (!newDbText.isEnabled()) {
                database = dbText.getSelectedItem().toString();
            } else {
                if (newDbText.getText().equals("")) {
                    logLabel.setForeground(Color.red);
                    logLabel.setText("Please select or specify a name \nfor the Database.");
                    return;
                } else {
                    database = newDbText.getText();
                }
            }

            host = hostText.getText();
            port = portText.getText();
            username = userText.getText();
            password = passwordText.getText();
        } catch (Exception e) {
            logLabel.setForeground(Color.red);
            logLabel.setText("Please choose a least one database or insert a new one.");
        }
        Component source = (Component) evt.getSource();
        int i = confirmPane.showConfirmDialog(source, "This operation will destory all data in the selected database. Are you sure?", "Database Replacement", JOptionPane.YES_NO_OPTION);
        if (i == 0) {
            try {
                createTables();
                new OlsrdDataSource(host, port, username, password, database);
            } catch (ClassNotFoundException ex) {
                logLabel.setText(ex.getMessage());
                Logger.getLogger(LatLonJsToMySQL.class.getName()).log(Level.SEVERE, null, ex);
            } catch (SQLException ex) {
                logLabel.setText(ex.getMessage());
                Logger.getLogger(LatLonJsToMySQL.class.getName()).log(Level.SEVERE, null, ex);
            } catch (Exception ex) {
                ex.getMessage();
            }
        } else {
            confirmPane.setVisible(false);
        }
}//GEN-LAST:event_startButtonActionPerformed

    private void checkconnButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_checkconnButtonActionPerformed
        try {
            host = hostText.getText();
            port = portText.getText();
            username = userText.getText();
            password = passwordText.getText();
            if (host.length() < 2) {
                if (port.length() == 0) {
                    port = "3306";
                }
                logLabel.setForeground(Color.red);
                logLabel.setText("Add host address and port number!");
            } else {
                logLabel.setText("Getting connection...");
                Class.forName("com.mysql.jdbc.Driver");
                c = (Connection) DriverManager.getConnection("jdbc:mysql://" + host + ":" + port, username, password);
                if (!c.isClosed()) {
                    dbText.setEnabled(true);
                    newDb.setEnabled(true);
                    startButton.setEnabled(true);
                    stmt = (Statement) c.createStatement();
                    rss = stmt.executeQuery("SHOW DATABASES");
                    int i = 0;
                    while (rss.next()) {
                        dbText.insertItemAt(rss.getString("Database"), i);
                        i++;
                        logLabel.setForeground(Color.green);
                        logLabel.setText("Connected!");
                        dbText.setSelectedIndex(0);
                        dbText.addItemListener(new java.awt.event.ItemListener() {

                            public void itemStateChanged(java.awt.event.ItemEvent evt) {
                                dbTextItemStateChanged(evt);
                            }
                        });
                        logLabel.setText("Now choose a database or create a new one.");
                    }
                }
            }
        } catch (Exception ex) {
            logLabel.setForeground(Color.red);
            logLabel.setText(ex.getMessage());
        }

    }//GEN-LAST:event_checkconnButtonActionPerformed

    private void createTables() throws ClassNotFoundException, SQLException {
        try {
            logLabel.setForeground(Color.black);
            logLabel.setText("Creating Table in " + database + " database...");
            Class.forName("com.mysql.jdbc.Driver");
            errors.put("DATABASE:", "Getting Connection for CreateTables...\n");
            logLabel.setText("Getting Connection for CreateTables...");

            String queryDel = "DROP SCHEMA IF EXISTS " + database + ";";

            String queryCreate = "CREATE SCHEMA IF NOT EXISTS " + database + ";";

            String queryUse = "use " + database + "; ";

            String query = "CREATE TABLE nodes (lon float DEFAULT '12.5535', "
                    + "lat float DEFAULT '41.8638', "
                    + "ip varchar(32) NOT NULL, "
                    + "name varchar(32) NOT NULL, "
                    + "isGateway binary(1) NOT NULL, "
                    + "gatewayIp varchar(32) NOT NULL, "
                    + "uptime varchar(10) DEFAULT NULL,"
                    + "interfaces varchar(50) DEFAULT NULL, "
                    + "PRIMARY KEY (name),KEY ip (ip)"
                    + ") ENGINE=InnoDB DEFAULT CHARSET=latin1; ";

            String query2 = "CREATE TABLE flows (RECNUM bigint(20) unsigned zerofill NOT NULL AUTO_INCREMENT, "
                    + "PROBE varchar(16) NOT NULL DEFAULT '',TIME_RECEIVED datetime NOT NULL DEFAULT '0000-00-00 00:00:00',"
                    + "FLOW_VERSION tinyint(4) NOT NULL DEFAULT '0',"
                    + "SEQUENCE bigint(20) unsigned zerofill NOT NULL DEFAULT '00000000000000000000',"
                    + "SOURCE_IP varchar(16) NOT NULL DEFAULT '',"
                    + "SOURCE_PORT int(11) NOT NULL DEFAULT '0',"
                    + "DEST_IP varchar(16) NOT NULL DEFAULT '',"
                    + "DEST_PORT int(11) NOT NULL DEFAULT '0',"
                    + "NEXT_HOP varchar(16) NOT NULL DEFAULT '',"
                    + "PROTOCOL int(11) NOT NULL DEFAULT '0',"
                    + "TCP_FLAGS int(11) NOT NULL DEFAULT '0',"
                    + "TOS int(11) NOT NULL DEFAULT '0',"
                    + "BYTES bigint(20) unsigned NOT NULL DEFAULT '0',"
                    + "PACKETS bigint(20) unsigned NOT NULL DEFAULT '0',"
                    + "FLOW_BEGIN datetime NOT NULL DEFAULT '0000-00-00 00:00:00',"
                    + "FLOW_END datetime NOT NULL DEFAULT '0000-00-00 00:00:00',"
                    + "SOURCE_AS int(11) NOT NULL DEFAULT '0',"
                    + "DEST_AS int(11) NOT NULL DEFAULT '0',"
                    + "SOURCE_MASK smallint(6) NOT NULL DEFAULT '0',"
                    + "DEST_MASK smallint(6) NOT NULL DEFAULT '0',"
                    + "PRIMARY KEY (RECNUM),KEY k_begin (FLOW_BEGIN),"
                    + "KEY k_end (FLOW_END),KEY k_time (TIME_RECEIVED),"
                    + "KEY k_src (SOURCE_IP),KEY k_dst (DEST_IP)"
                    + ") ENGINE=MyISAM DEFAULT CHARSET=latin1;";

            String query3 = "CREATE TABLE links (clock timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',"
                    + "src varchar(32) NOT NULL DEFAULT '',"
                    + "dest varchar(32) NOT NULL DEFAULT '',"
                    + "lq float DEFAULT NULL,"
                    + "nlq float DEFAULT NULL,"
                    + "etx float DEFAULT NULL,"
                    + "PRIMARY KEY (clock,src,dest),"
                    + "KEY src (src),"
                    + "KEY dest (dest),"
                    + "CONSTRAINT links_ibfk_2 FOREIGN KEY (dest) REFERENCES nodes (ip),"
                    + "CONSTRAINT links_ibfk_1 FOREIGN KEY (src) REFERENCES nodes (ip)"
                    + ") ENGINE=InnoDB DEFAULT CHARSET=latin1; ";

            String query4 = "CREATE TABLE layer ("
                    + "id int(11) NOT NULL AUTO_INCREMENT,"
                    + "srcnode varchar(32) DEFAULT NULL,"
                    + "clock varchar(10) NULL DEFAULT NULL,"
                    + "destnode varchar(32) DEFAULT NULL,"
                    + "PRIMARY KEY (id),"
                    + "KEY srcnode (srcnode),"
                    + "KEY destnode (destnode),"
                    + "CONSTRAINT layer_ibfk_2 FOREIGN KEY (destnode) REFERENCES links (dest),"
                    + "CONSTRAINT layer_ibfk_1 FOREIGN KEY (srcnode) REFERENCES links (src)"
                    + ") ENGINE=InnoDB DEFAULT CHARSET=latin1;";

            String query5 = "CREATE TABLE interfaces (mainIp varchar(32) NOT NULL DEFAULT '',"
                    + "IntIp varchar(32) DEFAULT NULL,"
                    + "KEY mainIp (mainIp)"
                    + ") ENGINE=InnoDB DEFAULT CHARSET=latin1";

            Connection c2 = (Connection) DriverManager.getConnection("jdbc:mysql://" + host + ":" + port, username, password);
            Statement stmt2 = (Statement) c2.createStatement();
            errors.put("DATABASE:", "Connected to the database...\n");
            logLabel.setText("Execute Queries...");

            Thread.sleep(3000);
            System.out.println(queryDel);
            System.out.println(queryCreate);
            System.out.println(queryUse);
            System.out.println(query);
            System.out.println(query2);
            System.out.println(query3);
            System.out.println(query4);
            System.out.println(query5);

            stmt2.executeUpdate(queryDel);
            errors.put("DATABASE_QUERY:", queryDel + "\n");

            stmt2.executeUpdate(queryCreate);
            errors.put("DATABASE_QUERY:", queryCreate + "\n");

            stmt2.executeQuery(queryUse);
            errors.put("DATABASE_QUERY:", queryUse + "\n");

            Thread.sleep(1000);
            stmt2.executeUpdate(query);
            errors.put("DATABASE_QUERY:", query + "\n");
            Thread.sleep(1000);

            stmt2.executeUpdate(query2);
            errors.put("DATABASE_QUERY:", query2 + "\n");
            Thread.sleep(1000);

            stmt2.executeUpdate(query3);
            errors.put("DATABASE_QUERY:", query3 + "\n");
            Thread.sleep(1000);

            stmt2.executeUpdate(query4);
            errors.put("DATABASE:", query4 + "\n");
            Thread.sleep(1000);

            stmt2.executeUpdate(query5);
            errors.put("DATABASE:", query5 + "\n");
            Thread.sleep(1000);

            errors.put("DATABASE:", "Now Adding nodes and Links....! This will take a while...\n");
            logLabel.setText("Now Adding nodes and Links....! This will take a while..");

        } catch (Exception e) {
            System.out.println(e.getMessage());
        }

    }

    private void showLogActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_showLogActionPerformed
        scrollPane.setSize(400, 300);
        errorsLog.append(errors.values().toString());
        frame = new Frame("Activity Log");
        frame.add(scrollPane);
        frame.setLayout(new FlowLayout());
        frame.setSize(400, 300);
        frame.setVisible(true);
        frame.addWindowListener(new WindowAdapter() {

            public void windowClosing(WindowEvent e) {
                frame.setVisible(false);


            }
        });
    }//GEN-LAST:event_showLogActionPerformed

    private void exampleButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_exampleButtonActionPerformed
        userText.setText("root");
        passwordText.setText("");
        hostText.setText("127.0.0.1");
    }//GEN-LAST:event_exampleButtonActionPerformed

    private void confirmPanePropertyChange(java.beans.PropertyChangeEvent evt) {//GEN-FIRST:event_confirmPanePropertyChange
        System.out.println("PopUp3");
        String prop = evt.getPropertyName();
        if (evt.getSource().equals(confirmPane) && prop.equals(JOptionPane.YES_OPTION)) {
            try {
                logLabel.setText("Getting connection...");
                Thread.sleep(1000);
                Class.forName("com.mysql.jdbc.Driver");
                c = (Connection) DriverManager.getConnection("jdbc:mysql://" + host + ":" + port + "/" + database, username, password);
                if (!c.isClosed()) {
                    logLabel.setForeground(Color.green);
                    logLabel.setText("Connected!");
                    createTables();
                    Thread.sleep(3000);
                }
            } catch (Exception ex) {
                logLabel.setText(ex.getMessage());
                Logger.getLogger(LatLonJsToMySQL.class.getName()).log(Level.SEVERE, null, ex);
            }
        } else {
            optionPane.setEnabled(false);
        }
    }//GEN-LAST:event_confirmPanePropertyChange

    private void newDbItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_newDbItemStateChanged
        if (newDb.isSelected()) {
            continueButton.setEnabled(false);
            resumeButton.setEnabled(false);
            startButton.setEnabled(true);
            newDbText.setEnabled(true);
            dbText.setEnabled(false);
            dbText.removeItemListener(new java.awt.event.ItemListener() {

                public void itemStateChanged(java.awt.event.ItemEvent evt) {
                    dbTextItemStateChanged(evt);
                }
            });
        } else if (!newDb.isSelected()) {
            newDbText.setEnabled(false);
            dbText.setEnabled(true);
            dbText.addItemListener(new java.awt.event.ItemListener() {

                public void itemStateChanged(java.awt.event.ItemEvent evt) {
                    dbTextItemStateChanged(evt);
                }
            });
        }
    }//GEN-LAST:event_newDbItemStateChanged

    private void continueButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_continueButtonActionPerformed
        OlsrdDataSource noStore = new OlsrdDataSource();
        noStore.init_nostore();
    }//GEN-LAST:event_continueButtonActionPerformed

    private void resumeButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_resumeButtonActionPerformed
        new OlsrdDataSource(host, port, username, password, selectedDatabase);
    }//GEN-LAST:event_resumeButtonActionPerformed

    private void dbTextItemStateChanged(java.awt.event.ItemEvent evt) {
        selectedDatabase = dbText.getSelectedItem().toString();
        host = hostText.getText();
        username = userText.getText();
        password = passwordText.getText();
        logLabel.setForeground(Color.green);

        logLabel.setText("Checking Database...please wait...");
        try {
            Class.forName("com.mysql.jdbc.Driver");
            c = (Connection) DriverManager.getConnection("jdbc:mysql://" + host + ":" + port + "/" + selectedDatabase, username, password);
            if (!c.isClosed()) {
                String selectedDB = dbText.getSelectedItem().toString();
                stmt = (Statement) c.createStatement();
                rss = stmt.executeQuery("SHOW TABLES");
                Vector<String> oktables = new Vector<String>();
                oktables.add("nodes");
                oktables.add("links");
                oktables.add("layer");
                oktables.add("flows");
                oktables.add("interfaces");
                Vector<String> tables = new Vector<String>();
                while (rss.next()) {
                    tables.add(rss.getString("Tables_in_" + selectedDB));
                }
                // System.out.println(tables);
                //System.out.println(oktables);
                if (selectedDB.equals("information_schema")) {
                    logLabel.setForeground(Color.RED);
                logLabel.setText("ATTENTION! Selected Database cannot be used!");
                } else {
                    if (tables.containsAll(oktables)) {
                        resumeButton.setEnabled(true);
                        continueButton.setEnabled(true);
                        logLabel.setForeground(Color.green);
                        logLabel.setText("This database already contains Freimap data.\n\nYou can resume storing by pressing\nresume button...");
                    } else {
                        if (resumeButton.isEnabled()) {
                            resumeButton.setEnabled(false);
                        }
                        startButton.setEnabled(true);
                        logLabel.setForeground(Color.RED);
                        logLabel.setText("ATTENTION!!! This database must be initialized for Freimap...\n\nALL DATA WILL BE DESTROYED!!");
                    }
                }
            }
        } catch (Exception ex) {
            logLabel.setText(ex.getMessage());
            Logger.getLogger(LatLonJsToMySQL.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public boolean controlDabatase() {
        try {
            host = hostText.getText();
            port = portText.getText();
            username = userText.getText();
            password = passwordText.getText();


            if (host.length() < 2) {
                if (port.length() == 0) {
                    port = "3306";


                }
                logLabel.setForeground(Color.red);
                logLabel.setText("Add host address and port number!");


                return false;


            } else {
                logLabel.setText("Check connection...");
                Thread.sleep(1000);
                Class.forName("com.mysql.jdbc.Driver");
                c = (Connection) DriverManager.getConnection("jdbc:mysql://" + host + ":" + port, username, password);


                if (!c.isClosed()) { //check the connection again....
                    stmt = (Statement) c.createStatement();
                    rss = stmt.executeQuery("SHOW DATABASES");
                    dbText.setEnabled(true);
                    newDb.setEnabled(true);


                    int i = 0;


                    while (rss.next()) {
                        dbText.insertItemAt(rss.getString("Database"), i);
                        i++;

                    }


                    logLabel.setForeground(Color.green);
                    logLabel.setText("Connected!");
                    Thread.sleep(1000);
                    logLabel.setText("Now choose a Database");


                    return true;


                }

            }
        } catch (Exception ex) {
            logLabel.setForeground(Color.red);
            logLabel.setText(ex.getMessage());


        }
        return false;


    }

    private String stripQuotes(String str) {
        if (str.length() <= 2) {
            return null;



        }
        return str.substring(1, str.length() - 1);



    }

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new LatLonJsToMySQL().setVisible(true);





            }
        });







    }
    Frame frame = null;
    Connection c = null;
    ResultSet rss = null;
    Statement stmt = null;
    String line = null;
    HashMap<String, String> errors = new HashMap<String, String>();
    String host;
    String username;
    String password;
    String database;
    String selectedDatabase;
    String port;
    JOptionPane optionPane = null;
    String path;
    private DataSource datas;
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton cancelButton;
    private javax.swing.JButton checkconnButton;
    private javax.swing.JOptionPane confirmPane;
    private javax.swing.JButton continueButton;
    private javax.swing.JComboBox dbText;
    private javax.swing.JTextArea errorsLog;
    private javax.swing.JButton exampleButton;
    private javax.swing.JTextField hostText;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JLabel logLabel;
    private javax.swing.JCheckBox newDb;
    private javax.swing.JTextField newDbText;
    private javax.swing.JPasswordField passwordText;
    private javax.swing.JTextField portText;
    private javax.swing.JButton resumeButton;
    private javax.swing.JScrollPane scrollPane;
    private javax.swing.JButton showLog;
    private javax.swing.JButton startButton;
    private javax.swing.JTextField userText;
    // End of variables declaration//GEN-END:variables
}
